package com.feishi.core.util.common.math;

import java.lang.reflect.Array;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: caixq
 * Date: 2018-12-26
 * Time: 下午1:03
 */
public class Item {
    public int op;
    public int index;
    public Item item;



    public boolean con(int j) {
        Item ite = this;
        while (ite!=null){
            if(ite.index==j){
                return true;
            }
            ite=ite.item;
        }
        return false;
    }



    private void ad(Item it) {
        Item ite = this;
        while (ite.item!=null){
            ite=ite.item;
        }
        ite.item=it;
    }

    @Override
    public String toString() {
        return "Item{" +
                "op=" + op +
                ", index=" + index +
                ", item=" + item +
                '}';
    }
    public String toString(Map<Integer,String> map){
        return (op==0?" + ":(op==1?" - ":(op==2?" * ":" / ")))+map.get(index)+(item==null?"::":item.toString(map));
    }

//
//    public boolean equals(Item obj) {
//        if(obj==null){
//            return false;
//        }
//        if(this.item==null){
//
//            return item.index==obj.index;
//        }
//        return item.index==obj.index&&this.item.equals(obj.item);
//    }


    @Override
    public boolean equals(Object obj) {
        return hashCode()==obj.hashCode();
    }

    @Override
    public int hashCode() {
        if(this.item==null){
            return this.index;
        }
        return this.index+16*item.op+item.hashCode()*64;
    }

    public static double js(double[] d, Item item) {
        double result=d[item.index];
        while (item.item!=null){
            item=item.item;
            switch(item.op){
                case 0: result+=d[item.index];break;
                case 1: result-=d[item.index];break;
                case 2: result*=d[item.index];break;
                case 3: result/=d[item.index];break;
            }
        }

        return result;
    }

    public int deep() {
        if(item==null){
            return 0;
        }
        return item.deep()+1;
    }

    public static double avs(double[] ds) {
        double sum=0;
        for (double d : ds) sum += d;
        double s1=0;
        for (double d : ds) {
            s1+=Math.abs(d-sum/ds.length);
        }


        return s1/sum;
    }
}
